<template>

  <div class="search-container">
    <!-- 头部搜索 -->
      <van-search
      class="search"
      v-model="searchText"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @cancel="onCancel"
      @focus="searchRes = false"
      />
    <!-- 组件进入 -->
      <!-- 搜索结果 -->
    <search-resolve v-if="searchRes" :search-text="searchText" />
      <!-- 搜索记录 如果输入框有值隐藏,显示搜索建议 -->
    <search-history v-else-if="!searchText" :history-list="historyList" @search="onSearch" @clear-history="historyList=[]"/>
      <!-- 搜索建议 如果输入框妹纸,显示搜索记录-->
    <search-sug @search="onSearch" v-else :search-text="searchText"/>

      <!-- 空状态 -->
      <van-empty v-if="!historyList.length" image="error" description="暂无搜索记录" />
  </div>
</template>

<script>
import searchResolve from './components/searchResolve.vue'
import searchSug from './components/searchSug.vue'
import searchHistory from './components/searchHistory.vue'
import { getItem, setItem } from '@/utils/storage.js'
export default {
  name: 'search',
  data () {
    return {
      searchText: '',
      searchRes: false, // 搜索结果flag
      historyList: getItem('HISTORY') || []
    }
  },
  components: {
    searchResolve,
    searchSug,
    searchHistory
  },
  watch: {
    historyList: {
      handler () {
        setItem('HISTORY', this.historyList)
      }
    }
  },
  methods: {
    onSearch (v) {
      if (v.trim().length === 0) return
      this.historyList.unshift(v)
      this.historyList = new Set(this.historyList)
      this.historyList = Array.from(this.historyList)
      this.searchText = v
      this.searchRes = true
    },
    onCancel () {
      this.$router.push('/')
    }
  }
}
</script>

<style scoped lang="less">
  .search-container {
    .van-search {
      background-color: #3296FA;
    }
    .van-search__action {
      color: #fff;
      &:focus {
        background-color: #3296FA;
      }
    }
    .search {
      position: sticky;
      top: 0;
      z-index: 100;
    }
  }
</style>
